package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExsitExcepthon;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.crypto.hash.Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.lang.reflect.Member;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 实现注册功能
     * @param vo
     */
    @Override
    public void regitst(MemberRegistVo vo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = new MemberEntity();
        //设置默认会员等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());

        //检查用户名和手机号是否唯一
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());

        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());
        entity.setNickname(vo.getUserName());
        //密码需要加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);
        //其他默认信息
        memberDao.insert(entity);

    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExsitExcepthon {
        MemberDao memberDao = this.baseMapper;
        Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(mobile > 0){
            throw new PhoneExsitExcepthon();
        }

    }

    @Override
    public void checkUserNameUnique(String username) throws UsernameExistException{
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if(count > 0){
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        //1.去数据库查询
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct)
                .or().eq("mobile", loginacct));
        if(entity == null){
            return null;
        }
        else{
            //获取到数据库的password
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //进行密码匹配
            boolean matches = passwordEncoder.matches(password, passwordDb);
            if(matches){
                return entity;
            }
            else{
                return null;
            }
        }

    }

    @Override
    public MemberEntity login(SocialUser socialUserTo) {
        MemberEntity entityByUid = this.getOne(new QueryWrapper<MemberEntity>().eq("social_uid", socialUserTo.getId()));
        //1.如果之前未登录过，封装社交信息
        if (entityByUid == null){

            String json = null;
            try {

                Map<String,String> queryAccessToken = new HashMap<>();
                queryAccessToken.put("access_token",socialUserTo.getAccess_token());

                Map<String,String> queryHeader = new HashMap<>();
                queryHeader.put("Content-Type","application/json;charset=UTF-8");

                //发送请求
                //https://gitee.com/api/v5/user?access_token={access_token}
                HttpResponse response1 = HttpUtils.doGet("https://gitee.com","/api/v5/user","get",queryHeader,queryAccessToken);


                json = EntityUtils.toString(response1.getEntity());
            } catch (Exception e) {
                e.printStackTrace();
            }

            entityByUid = new MemberEntity();
            entityByUid.setAccessToken(socialUserTo.getAccess_token());
            entityByUid.setSocialUid(socialUserTo.getId());
            entityByUid.setExpiresIn(socialUserTo.getExpires_in());
//            MemberLevelEntity defaultLevel = MemberLevelService.getOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1));
//            entityByUid.setLevelId(defaultLevel.getId());

            // 第三方信息
            JSONObject jsonObject = JSON.parseObject(json);
            // 昵称、头像
            String name = jsonObject.getString("name");
            String profile_image_url = jsonObject.getString("avatar_url");
            //这个 service 查询的
            entityByUid.setNickname(name);
            entityByUid.setHeader(profile_image_url);

            this.save(entityByUid);
        }else {
            //2.否则更新令牌等信息并返回
            entityByUid.setAccessToken(socialUserTo.getAccess_token());
            entityByUid.setSocialUid(socialUserTo.getId());
            entityByUid.setExpiresIn(socialUserTo.getExpires_in());
            entityByUid.setHeader(socialUserTo.getAvatar_url());
            entityByUid.setNickname(socialUserTo.getName());
        }
        return entityByUid;
    }


}